<template>
  <div class="users-page">
    <div class="page-header">
      <div class="header-left">
        <h1 class="page-title">用户管理</h1>
        <p class="page-subtitle">管理系统用户及其权限</p>
      </div>
      <div class="header-right">
        <a-button type="primary" @click="showAddUserModal">
          <PlusOutlined /> 添加用户
        </a-button>
      </div>
    </div>

    <div class="users-content">
      <a-card :bordered="false">
        <!-- Filters -->
        <div class="filters-bar">
          <a-space>
            <a-input-search
              v-model:value="filters.search"
              placeholder="搜索用户名、邮箱..."
              style="width: 300px"
              @search="loadUsers"
            />
            <a-select
              v-model:value="filters.role"
              placeholder="角色筛选"
              style="width: 150px"
              allowClear
              @change="loadUsers"
            >
              <a-select-option value="admin">管理员</a-select-option>
              <a-select-option value="operator">运维人员</a-select-option>
              <a-select-option value="developer">开发人员</a-select-option>
              <a-select-option value="viewer">观察员</a-select-option>
            </a-select>
            <a-select
              v-model:value="filters.status"
              placeholder="状态筛选"
              style="width: 120px"
              allowClear
              @change="loadUsers"
            >
              <a-select-option value="active">活跃</a-select-option>
              <a-select-option value="inactive">未激活</a-select-option>
              <a-select-option value="locked">已锁定</a-select-option>
            </a-select>
          </a-space>
        </div>

        <!-- Users Table -->
        <a-table
          :columns="columns"
          :data-source="users"
          :loading="loading"
          :pagination="pagination"
          @change="handleTableChange"
          row-key="_id"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'username'">
              <a-space>
                <a-avatar :src="record.avatar" :style="{ backgroundColor: record.avatarColor || '#667eea' }">
                  {{ record.username.charAt(0).toUpperCase() }}
                </a-avatar>
                <span class="username">{{ record.username }}</span>
              </a-space>
            </template>

            <template v-else-if="column.key === 'role'">
              <a-tag :color="getRoleColor(record.role)">
                {{ getRoleLabel(record.role) }}
              </a-tag>
            </template>

            <template v-else-if="column.key === 'status'">
              <a-badge
                :status="record.isActive ? 'success' : 'default'"
                :text="record.isActive ? '活跃' : '未激活'"
              />
            </template>

            <template v-else-if="column.key === 'lastLogin'">
              {{ record.lastLogin ? formatDate(record.lastLogin) : '从未登录' }}
            </template>

            <template v-else-if="column.key === 'createdAt'">
              {{ formatDate(record.createdAt) }}
            </template>

            <template v-else-if="column.key === 'actions'">
              <a-space>
                <a-button type="link" size="small" @click="editUser(record)">
                  编辑
                </a-button>
                <a-button
                  type="link"
                  size="small"
                  @click="resetPassword(record)"
                >
                  重置密码
                </a-button>
                <a-button
                  type="link"
                  size="small"
                  danger
                  @click="deleteUser(record)"
                >
                  删除
                </a-button>
              </a-space>
            </template>
          </template>
        </a-table>
      </a-card>
    </div>

    <!-- Add/Edit User Modal -->
    <a-modal
      v-model:open="userModalVisible"
      :title="editingUser ? '编辑用户' : '添加用户'"
      :confirm-loading="modalLoading"
      @ok="handleUserSubmit"
      @cancel="handleUserCancel"
      width="600px"
    >
      <a-form
        ref="userFormRef"
        :model="userForm"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-item
          label="用户名"
          name="username"
          :rules="[{ required: true, message: '请输入用户名' }]"
        >
          <a-input v-model:value="userForm.username" placeholder="请输入用户名" />
        </a-form-item>

        <a-form-item
          label="邮箱"
          name="email"
          :rules="[
            { required: true, message: '请输入邮箱' },
            { type: 'email', message: '请输入有效的邮箱地址' }
          ]"
        >
          <a-input v-model:value="userForm.email" placeholder="请输入邮箱" />
        </a-form-item>

        <a-form-item
          v-if="!editingUser"
          label="密码"
          name="password"
          :rules="[
            { required: true, message: '请输入密码' },
            { min: 6, message: '密码至少6个字符' }
          ]"
        >
          <a-input-password v-model:value="userForm.password" placeholder="请输入密码" />
        </a-form-item>

        <a-form-item
          label="角色"
          name="role"
          :rules="[{ required: true, message: '请选择角色' }]"
        >
          <a-select v-model:value="userForm.role" placeholder="请选择角色">
            <a-select-option value="admin">管理员</a-select-option>
            <a-select-option value="operator">运维人员</a-select-option>
            <a-select-option value="developer">开发人员</a-select-option>
            <a-select-option value="viewer">观察员</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="真实姓名" name="realName">
          <a-input v-model:value="userForm.realName" placeholder="请输入真实姓名" />
        </a-form-item>

        <a-form-item label="电话" name="phone">
          <a-input v-model:value="userForm.phone" placeholder="请输入电话号码" />
        </a-form-item>

        <a-form-item label="部门" name="department">
          <a-input v-model:value="userForm.department" placeholder="请输入部门" />
        </a-form-item>

        <a-form-item label="激活状态" name="isActive">
          <a-switch v-model:checked="userForm.isActive" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue'
import type { TableColumnType, TableProps } from 'ant-design-vue'
import { h } from 'vue'
import dayjs from 'dayjs'

interface User {
  _id: string
  username: string
  email: string
  role: string
  realName?: string
  phone?: string
  department?: string
  isActive: boolean
  lastLogin?: string
  createdAt: string
  avatar?: string
  avatarColor?: string
}

interface UserForm {
  username: string
  email: string
  password?: string
  role: string
  realName?: string
  phone?: string
  department?: string
  isActive: boolean
}

const loading = ref(false)
const users = ref<User[]>([])
const userModalVisible = ref(false)
const modalLoading = ref(false)
const editingUser = ref<User | null>(null)
const userFormRef = ref()

const filters = reactive({
  search: '',
  role: undefined as string | undefined,
  status: undefined as string | undefined,
})

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
})

const userForm = reactive<UserForm>({
  username: '',
  email: '',
  password: '',
  role: '',
  realName: '',
  phone: '',
  department: '',
  isActive: true,
})

const columns: TableColumnType<User>[] = [
  {
    title: '用户名',
    dataIndex: 'username',
    key: 'username',
    width: 200,
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    key: 'email',
  },
  {
    title: '角色',
    dataIndex: 'role',
    key: 'role',
    width: 120,
  },
  {
    title: '部门',
    dataIndex: 'department',
    key: 'department',
    width: 120,
  },
  {
    title: '状态',
    key: 'status',
    width: 100,
  },
  {
    title: '最后登录',
    key: 'lastLogin',
    width: 180,
  },
  {
    title: '创建时间',
    key: 'createdAt',
    width: 180,
  },
  {
    title: '操作',
    key: 'actions',
    width: 240,
    fixed: 'right',
  },
]

const loadUsers = async () => {
  try {
    loading.value = true

    // TODO: Replace with actual API call when backend user management endpoints are ready
    // For now, using mock data
    const mockUsers: User[] = [
      {
        _id: '1',
        username: 'admin',
        email: 'admin@devops.com',
        role: 'admin',
        department: '技术部',
        isActive: true,
        lastLogin: new Date().toISOString(),
        createdAt: '2024-01-01T00:00:00Z',
        avatarColor: '#f56a00',
      },
      {
        _id: '2',
        username: 'operator1',
        email: 'operator@devops.com',
        role: 'operator',
        department: '运维部',
        isActive: true,
        lastLogin: new Date(Date.now() - 3600000).toISOString(),
        createdAt: '2024-02-01T00:00:00Z',
        avatarColor: '#7265e6',
      },
      {
        _id: '3',
        username: 'developer1',
        email: 'dev@devops.com',
        role: 'developer',
        department: '开发部',
        isActive: true,
        createdAt: '2024-03-01T00:00:00Z',
        avatarColor: '#00a2ae',
      },
    ]

    users.value = mockUsers
    pagination.total = mockUsers.length
  } catch (error) {
    console.error('Failed to load users:', error)
    message.error('加载用户列表失败')
  } finally {
    loading.value = false
  }
}

const handleTableChange: TableProps['onChange'] = (pag, filters, sorter) => {
  pagination.current = pag.current || 1
  pagination.pageSize = pag.pageSize || 10
  loadUsers()
}

const showAddUserModal = () => {
  editingUser.value = null
  resetUserForm()
  userModalVisible.value = true
}

const editUser = (user: User) => {
  editingUser.value = user
  userForm.username = user.username
  userForm.email = user.email
  userForm.role = user.role
  userForm.realName = user.realName
  userForm.phone = user.phone
  userForm.department = user.department
  userForm.isActive = user.isActive
  userModalVisible.value = true
}

const handleUserSubmit = async () => {
  try {
    await userFormRef.value.validate()
    modalLoading.value = true

    // TODO: Replace with actual API call
    if (editingUser.value) {
      // Update user
      console.log('Update user:', editingUser.value._id, userForm)
      message.success('用户更新成功')
    } else {
      // Create user
      console.log('Create user:', userForm)
      message.success('用户创建成功')
    }

    userModalVisible.value = false
    await loadUsers()
  } catch (error) {
    console.error('Failed to submit user:', error)
    message.error(editingUser.value ? '用户更新失败' : '用户创建失败')
  } finally {
    modalLoading.value = false
  }
}

const handleUserCancel = () => {
  userModalVisible.value = false
  resetUserForm()
}

const resetUserForm = () => {
  userForm.username = ''
  userForm.email = ''
  userForm.password = ''
  userForm.role = ''
  userForm.realName = ''
  userForm.phone = ''
  userForm.department = ''
  userForm.isActive = true
  userFormRef.value?.resetFields()
}

const resetPassword = (user: User) => {
  Modal.confirm({
    title: '重置密码',
    icon: h(ExclamationCircleOutlined),
    content: `确定要重置用户 ${user.username} 的密码吗？新密码将发送到用户邮箱。`,
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      try {
        // TODO: Replace with actual API call
        console.log('Reset password for user:', user._id)
        message.success('密码重置成功，新密码已发送到用户邮箱')
      } catch (error) {
        console.error('Failed to reset password:', error)
        message.error('密码重置失败')
      }
    },
  })
}

const deleteUser = (user: User) => {
  Modal.confirm({
    title: '删除用户',
    icon: h(ExclamationCircleOutlined),
    content: `确定要删除用户 ${user.username} 吗？此操作不可恢复。`,
    okText: '确定',
    okType: 'danger',
    cancelText: '取消',
    onOk: async () => {
      try {
        // TODO: Replace with actual API call
        console.log('Delete user:', user._id)
        message.success('用户删除成功')
        await loadUsers()
      } catch (error) {
        console.error('Failed to delete user:', error)
        message.error('用户删除失败')
      }
    },
  })
}

const getRoleColor = (role: string): string => {
  const colors: Record<string, string> = {
    admin: 'red',
    operator: 'blue',
    developer: 'green',
    viewer: 'default',
  }
  return colors[role] || 'default'
}

const getRoleLabel = (role: string): string => {
  const labels: Record<string, string> = {
    admin: '管理员',
    operator: '运维人员',
    developer: '开发人员',
    viewer: '观察员',
  }
  return labels[role] || role
}

const formatDate = (date: string): string => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

onMounted(() => {
  loadUsers()
})
</script>

<style scoped lang="scss">
.users-page {
  height: 100%;
  overflow: auto;
  background: #f5f5f5;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 24px;
  border-bottom: 1px solid #f0f0f0;

  .page-title {
    margin: 0;
    font-size: 24px;
    font-weight: 600;
  }

  .page-subtitle {
    margin: 4px 0 0;
    color: #8c8c8c;
    font-size: 14px;
  }
}

.users-content {
  padding: 24px;

  .filters-bar {
    margin-bottom: 16px;
  }

  .username {
    font-weight: 500;
  }
}
</style>
